//
//  RecommendViewController.swift
//  liveDemo
//
//  Created by satoshi_uma on 2020/10/22.
//  Copyright © 2020 satoshi_uma. All rights reserved.
//

import UIKit

let itemMargin: CGFloat = 10
let ItemW = (SCREEN_WIDTH - 3 * itemMargin) / 2
let ItemNormalH = (ItemW * 3) / 4
let ItemPrettyH = (ItemW * 4) / 3

let HeaderViewH: CGFloat = 50

let NormalCellID: String = "ID"
let HeaderViewID: String = "headerID"
let PrettyCellID: String = "PrettyID"

class RecommendViewController: UIViewController {
//    系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()

        getNetworkData()

//        设置UI界面内容
        setupUI()
    }

    private lazy var collectionView: UICollectionView = { [unowned self] in

        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: ItemW, height: ItemNormalH)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = itemMargin // 行间距
        layout.headerReferenceSize = CGSize(width: SCREEN_WIDTH, height: HeaderViewH)
        layout.sectionInset = UIEdgeInsets(top: 0, left: itemMargin, bottom: 0, right: itemMargin)

        let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.white
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] // 随着父控件的拉伸而拉伸

        //        注册 cell 表头
        collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: HeaderViewID)
        //        注册 cell
        collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: NormalCellID)
        collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: PrettyCellID)

        return collectionView
    }()

    private lazy var dataArr: [AnchorGroup] = [AnchorGroup]()
}

// 设置UI界面内容
extension RecommendViewController {
    /// 设置UI
    private func setupUI() {
        view.addSubview(collectionView)
    }
}

// UICollectionViewDataSource
extension RecommendViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        if section == 0 {
            return self.dataArr.count
//        } else { return 4 }
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
//        var cell: UICollectionViewCell!

        let anchorGroup = self.dataArr[indexPath.item]
        
        if indexPath.section == 1 {
           let prettyCell = collectionView.dequeueReusableCell(withReuseIdentifier: PrettyCellID, for: indexPath) as! CollectionPrettyCell
            return prettyCell
        } else {
           let normalCell = collectionView.dequeueReusableCell(withReuseIdentifier: NormalCellID, for: indexPath) as! CollectionNormalCell
            
            normalCell.anchorGroup = anchorGroup
            return normalCell
        }
        
    }

//    表头视图
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: HeaderViewID, for: indexPath)

        return headView
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if indexPath.section == 1 {
            return CGSize(width: ItemW, height: ItemPrettyH)
        }
        return CGSize(width: ItemW, height: ItemNormalH)
    }
}

// UICollectionViewDelegate
extension RecommendViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
        print("didHighlightItemAt\(indexPath.row)")
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("\(indexPath.row)")
    }
}

//
extension RecommendViewController {
    /// 获取网络数据
    private func getNetworkData() {
        let URL = "https://way.jd.com/jisuapi/get"
        NetworkTools.requestData(type: .get,
                                 URL: URL,
                                 parameter: ["channel": "头条", "num": "30", "start": "0", "appkey": "d1f1032d73a8ab59a6b5289e9b05e04b"]) { result, error in

            guard let resultNew = result as? [String: NSObject] else { return }
            guard let resultDic = resultNew["result"] as? [String: NSObject] else { return }
            guard let result_resultDic = resultDic["result"] as? [String: NSObject] else { return }
            guard let result_resultDic_Arr = result_resultDic["list"] as? [[String: NSObject]] else { return }

            for dic in result_resultDic_Arr {
                let anchorGroup = AnchorGroup(dict: dic)
                self.dataArr.append(anchorGroup)
            }

            for dict in self.dataArr {
                print("result_resultDic_Arr_dic: \(dict.pic)")
            }

                                    self.collectionView.reloadData()
            print("result_success________: \(result)")
            print("result_error__________: \(error)")
        }
    }
}
